package com.ytjj.qmyx.mall.controller.taoxingou;

import com.alibaba.fastjson.JSONArray;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.controller.BaseController;
import com.ytjj.common.exception.ApiException;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.TokenUtil;
import com.ytjj.qmyx.mall.config.CommonPropertiesConfig;
import com.ytjj.qmyx.mall.model.SpecialRank;
import com.ytjj.qmyx.mall.model.response.ActivityProductResponse;
import com.ytjj.qmyx.mall.service.ActivityService;
import com.ytjj.qmyx.mall.service.OrdersService;
import com.ytjj.qmyx.mall.service.ProductService;
import com.ytjj.qmyx.mall.service.SpecialRankService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * XXXX优品-活动通用控制器（固定获取h5销售端商品）
 */
@RestController
@RequestMapping("/gcyp/activity")
public class GcypCommonActivityController extends BaseController {
    @Autowired
    private ActivityService activityService;
    @Autowired
    private SpecialRankService specialRankService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private ProductService productService;
    @Autowired
    private OrdersService ordersService;
    @Autowired
    private CommonPropertiesConfig commonPropertiesConfig;

    /**
     *
     * @param activityType 活动类型
     * @param columnIds    活动栏目，多个用','分隔
     * @param pageSizes    每个columnId查询条数，多个用','分隔(同上面的columnIds一一对应)
     * @param flag         是否乱序 1-乱序 其它不乱序
     * @return             返回map格式 比如columnIds="1,2,3" 则返回的key分别为：key1、key2、key3
     */
    @GetMapping("index")
    public CommonResult index (@RequestParam("activityType") String activityType,
                               @RequestParam(value = "columnIds", required = false) String columnIds,
                               @RequestParam(value = "pageSizes", required = false) String pageSizes,
                               @RequestParam(value = "flag", required = false) Integer flag) {
        if (StringUtils.isEmpty(activityType)) {
            throw new ApiException("参数错误！");
        }
        if (StringUtils.isEmpty(columnIds)) {
            throw new ApiException("活动栏目不能为空！");
        }
        String[] pageSizeArr = null;
        if (!StringUtils.isEmpty(pageSizes)) {
            pageSizeArr = pageSizes.split(",");
        }
        Map<String, Object> result = new HashMap();
        AtomicInteger index = new AtomicInteger(0);
        String[] finalPageSizeArr = pageSizeArr;
        Arrays.stream(columnIds.split(",")).forEach(item -> {
            int pageSize = 20;
            int key_index = index.get();
            String key = "key" + (key_index + 1);
            if (null != finalPageSizeArr && finalPageSizeArr.length >= index.get()) {
                pageSize = Integer.parseInt(finalPageSizeArr[index.getAndAdd(1)]);
            }
            List<ActivityProductResponse> productList = activityService.getActivityList(1,
                    pageSize <= 0 ? 20 : pageSize,
                    activityType,
                    Integer.parseInt(item),"h5");
            if (1 == flag) {
                Collections.shuffle(productList);
            }
            result.put(key, productList);
        });
        return CommonResult.success(result);
    }

    /**
     * 获取栏目商品列表
     * @param activityType 活动类型
     * @param columnId      活动栏目id
     * @param pageSize      查询多少条
     * @param pageNum       第多少页
     * @param flag          是否需要打乱顺序 1-打乱
     * @return
     */
    @GetMapping("/queryListByPage")
    public CommonResult queryListByPage(@RequestParam(value = "activityType") String activityType,
                                        @RequestParam(value = "columnId", required = false, defaultValue = "0") Integer columnId,
                                        @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize,
                                        @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                                        @RequestParam(value = "flag", required = false, defaultValue = "0") Integer flag) {
        List<ActivityProductResponse> productList = activityService.getActivityList(pageNum, pageSize, activityType, columnId,"h5");
        if(1==flag){//打乱顺序
            Collections.shuffle(productList);
        }
        return CommonResult.success(productList);
    }

    /**
     * 获取多个栏目商品列表
     * @param activityType 活动类型
     * @param columnIds      活动栏目id(用','分割)
     * @param pageSize      查询多少条
     * @param pageNum       第多少页
     * @param flag          是否需要打乱顺序 1-打乱
     * @return
     */
    @GetMapping("/queryListByColumnIds")
    public CommonResult queryListByColumnIds(@RequestParam(value = "activityType") String activityType,
                                        @RequestParam(value = "columnIds", required = false, defaultValue = "0") String columnIds,
                                        @RequestParam(value = "pageSize", required = false, defaultValue = "20") Integer pageSize,
                                        @RequestParam(value = "pageNum", required = false, defaultValue = "1") Integer pageNum,
                                        @RequestParam(value = "flag", required = false, defaultValue = "0") Integer flag) {

        List<ActivityProductResponse> productList = activityService.getActivityListByColumnIds(pageNum, pageSize, activityType, columnIds,"h5");
        if(1==flag){//打乱顺序
            Collections.shuffle(productList);
        }
        return CommonResult.success(productList);
    }

    /**
     * 查分类榜单
     * @param specialIds 分类id 总榜时传null; 多个用','分隔
     * @return
     */
    @GetMapping("/rank")
    public CommonResult queryRankListBySpecialId(@RequestParam("specialIds") String specialIds,Integer mark) {
        List<Map<String, Object>> result = new ArrayList<>();
        String platformData = TokenUtil.getPlatformData();
        if(mark != null && mark == 1){
            platformData = commonPropertiesConfig.getPlatformByIp();
        }
        //总榜单key
        String rank_total_key = "special:rank:total:" + platformData;
        //单个分类key
        StringBuilder rank_special_key = new StringBuilder("special:rank:single:").append(platformData).append(":");

        List<String> specialIdList = Arrays.asList(specialIds.split(","));
        List<SpecialRank> rankList = null;
        if (1 == specialIdList.size() && specialIdList.get(0).equals("0")) {
            //为空查总榜
            String rank_total_value = redisService.get(rank_total_key);
            if (StringUtils.isEmpty(rank_total_value)) {
                rankList = specialRankService.selectBySpecialId(null, platformData, 3);
                redisService.set(rank_total_key, JSONArray.toJSONString(rankList));
                redisService.expire(rank_total_key, 60 * 60);
            }else {
                rankList = JSONArray.parseArray(rank_total_value, SpecialRank.class);
            }
            Map<String, Object> map = new HashMap<>();
            map.put("total", rankList);
            Integer volumeNum = productService.sumProductVolumeByActivityType("CASH_SCORE");
//            Integer orderVolumeNum = ordersService.sumOrderVolumeByActivityType("CASH_SCORE");
            Integer orderVolumeNum = 0;
            map.put("volume", (null == volumeNum ? 0 : volumeNum) + (null == orderVolumeNum ? 0 : orderVolumeNum));
            result.add(map);
            return CommonResult.success(result);
        }

        if (1 == specialIdList.size()) {
            //查单个分类
            rank_special_key = rank_special_key.append(specialIdList.get(0));
            String rank_special_value = redisService.get(rank_special_key.toString());
            if (StringUtils.isEmpty(rank_special_value)) {
                rankList = specialRankService.selectBySpecialId(Integer.parseInt(specialIdList.get(0)), platformData, 3);
                redisService.set(rank_special_key.toString(), JSONArray.toJSONString(rankList));
                redisService.expire(rank_special_key.toString(), 5 * 60);
            }else {
                rankList = JSONArray.parseArray(rank_special_value, SpecialRank.class);
            }
            Map<String, Object> map = new HashMap<>();
            map.put(specialIdList.get(0), rankList);
            result.add(map);
            return CommonResult.success(result);
        }

        //查多个时
        StringBuilder finalRank_special_key = rank_special_key;
        String finalPlatformData = platformData;
        specialIdList.stream().forEach(specialId -> {
            Map<String, Object> map = new HashMap<>();
            String rank_special_key_single = finalRank_special_key.append(specialId).toString();
            String redisVal = redisService.get(rank_special_key_single);
            if (StringUtils.isEmpty(redisVal)) {
                List<SpecialRank> ranks = specialRankService.selectBySpecialId(Integer.parseInt(specialId), finalPlatformData, 3);
                redisService.set(rank_special_key_single, JSONArray.toJSONString(ranks));
                redisService.expire(rank_special_key_single, 24 * 60 * 60);
                map.put(specialId, ranks);
            }else {
                List<SpecialRank> ranks = JSONArray.parseArray(redisVal, SpecialRank.class);
                map.put(specialId, ranks);
            }
            result.add(map);
        });
        return CommonResult.success(result);
    }

    /**
     * 查询分类榜单商品列表
     * @param specialId 分类id
     * @param pageSize  页大小
     * @param pageNum   页码
     * @return
     */
    @GetMapping("/rank/products/{specialId}")
    public CommonResult rankProductList(@PathVariable(name = "specialId") Integer specialId, Integer pageSize, Integer pageNum,Integer mark) {
        String platformData = TokenUtil.getPlatformData();
        if(mark != null && 1 == mark){
            platformData = commonPropertiesConfig.getPlatformByIp();
        }
        List<SpecialRank> ranks = specialRankService.selectBySpecialId(specialId, platformData, 50);
        if (CollectionUtils.isEmpty(ranks)) {
            return CommonResult.success();
        }
        List<Integer> productIds = ranks.stream().map(SpecialRank::getProductId).collect(Collectors.toList());
        List<ActivityProductResponse> activityProductResponses = activityService.queryActivityRankList(specialId, productIds, pageNum, pageSize);
        return CommonResult.success(activityProductResponses);
    }
}
